import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { tokenStore } from '@/store/token'
import { menuStore } from '@/store/menu'
// 理由地址配置
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: 'login' */ '@/page/login/login.vue')
  },
  {
    path: '/403',
    name: '403',
    component: () => import(/* webpackChunkName: 'swagger' */ '@/page/home/main/common/403Error.vue')
  },
  {
    path: '/404',
    name: '404',
    component: () => import(/* webpackChunkName: 'swagger' */ '@/page/home/main/common/404Error.vue')
  },
  {
    path: '/500',
    name: '500',
    component: () => import(/* webpackChunkName: 'swagger' */ '@/page/home/main/common/500Error.vue')
  },
  {
    path: '/home',
    name: 'home',
    component: () => import(/* webpackChunkName: 'swagger' */ '@/page/home/home.vue'),
    children: [
      {
        path: '/userinfo',
        name: '个人中心',
        component: () => import(/* webpackChunkName: 'swagger' */ '@/page/home/main/system/admin/user/userInfo.vue'),
        meta: {
          header: '个人中心',
          type: {
            desc: '个人中心',
            name: 'C'
          }
        }
      }
    ]
  },
  {
    path: '/',
    name: 'router',
    component: () => import(/* webpackChunkName: 'swagger' */ '@/page/home/home.vue')
  }
]

// 添加到创建的路由中
const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach(async (to, from, next) => {
  if (!router || !to.path || !from.path) {
    await Sleep(1500)
    next({ path: '/500' })
    return false
  }
  const userstore = tokenStore()
  // 判断是否登录
  switch (to.path) {
    case '/500':
    case '/404':
    case '/403':
    case '/swagger':
    case '/login':
      next()
      break
    default:
      // eslint-disable-next-line no-case-declarations
      if (!userstore || !userstore.token) {
        next({ path: '/login' })
        break
      } else {
        // 获取路由信息
        if (router.getRoutes().length <= routes.length + 1) {
          const menuStores = menuStore()
          await menuStores
            .toSetMenu()
            .then(() => {
              next({ ...to })
            })
            .catch(() => {
              next({ path: '/login' })
            })
          break
        } else {
          next()
          break
        }
      }
  }
  return false
})
export default router
